import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

export function createServer(): McpServer {
  const server = new McpServer({
    name: "Emoji Analyzer MCP Server",
    version: "1.0.0",
    description: "Analyzes emoji usage in text and provides detailed statistics",
  });

  server.tool(
    "analyze_emojis",
    "分析文本中的表情符号使用情况",
    {
      text: z.string().describe("要分析的文本内容"),
      detailed: z.boolean().optional().default(false)
        .describe("是否返回详细的表情符号分类统计"),
    },
    async ({ text, detailed }) => {
      try {
        // 扩展的表情符号正则表达式（支持更多emoji类别）
        const emojiRegex = /[\p{Emoji_Presentation}\p{Emoji}\p{Emoji_Modifier}\p{Emoji_Component}]/gu;
        const emojis = text.match(emojiRegex) || [];
        
        // 基础统计
        const result: any = {
          textLength: text.length,
          emojiCount: emojis.length,
          emojiDensity: emojis.length / text.length,
          uniqueEmojis: [...new Set(emojis)].length,
          textWithoutEmojis: text.replace(emojiRegex, ''),
          emojiFrequency: emojis.reduce((acc, emoji) => {
            acc[emoji] = (acc[emoji] || 0) + 1;
            return acc;
          }, {} as Record<string, number>)
        };

        // 如果需要详细统计
        if (detailed) {
          // 表情符号分类统计
          result.categories = {
            faces: emojis.filter(e => /\p{Emoji_Modifier}/u.test(e)).length,
            objects: emojis.filter(e => /[\u{1F300}-\u{1F5FF}]/u.test(e)).length,
            symbols: emojis.filter(e => /[\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/u.test(e)).length,
            flags: emojis.filter(e => /[\u{1F1E6}-\u{1F1FF}]/u.test(e)).length,
            animals: emojis.filter(e => /[\u{1F400}-\u{1F4D3}]/u.test(e)).length,
            food: emojis.filter(e => /[\u{1F32D}-\u{1F37F}]/u.test(e)).length,
          };

          // 最常用表情符号
          console.log("1212")
          result.topEmojis = Object.entries(result.emojiFrequency)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 5)
            .map(([emoji, count]) => ({ emoji, count }));
        }

        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, (key, value) => {
                // 美化JSON输出，处理特殊字符
                return typeof value === 'string' 
                  ? value.replace(/\\u\{([0-9A-Fa-f]+)\}/g, (_, code) => 
                      String.fromCodePoint(parseInt(code, 16)))
                  : value;
              }, 2)
            }
          ]
        };
      } catch (error) {
        console.error("表情符号分析失败:", error);
        return {
          content: [
            {
              type: "text",
              text: "表情符号分析服务暂时不可用"
            }
          ]
        };
      }
    }
  );

  return server;
}